package levelrewind.android.app;

import java.util.ArrayList;
import java.util.Arrays;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import levelrewind.android.app.model.RestDataHandler;
import levelrewind.android.app.model.Util;
import levelrewind.android.app.vo.User;

import com.facebook.*;
import com.facebook.model.*;
import com.facebook.widget.*;
import com.facebook.widget.WebDialog.OnCompleteListener;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class FacebookFragment extends Fragment {
	
	private static final String TAG = "MainFragment";
	private UiLifecycleHelper uiHelper;
	
	private TextView txtUserName;
	private ProfilePictureView profilePictureView;
	
	public static User loggedInUser;
	public static ArrayList<User> friends;

	private Session.StatusCallback callback = new Session.StatusCallback() {
	    @Override
	    public void call(Session session, SessionState state, Exception exception) {
	        onSessionStateChange(session, state, exception);
	    }
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    uiHelper = new UiLifecycleHelper(getActivity(), callback);
	    uiHelper.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, 
	        ViewGroup container, 
	        Bundle savedInstanceState) {
	    View view = inflater.inflate(R.layout.facebook_layout, container, false);
	    LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
	    authButton.setFragment(this);
	    authButton.setReadPermissions(Arrays.asList("email"));
	    
	    // Find the user's profile picture custom view
	    profilePictureView = (ProfilePictureView) view.findViewById(R.id.fb_pic);
	    profilePictureView.setCropped(true);
	    
	    txtUserName = (TextView) view.findViewById(R.id.welcomeNameTxt);
	    txtUserName.setTypeface(Util.customFont(this.getActivity()));
	    
	    return view;
	}
	
	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
		
		//TODO: ERROR WHEN LOGIN AT FIRST TIME, get double data
		// Initial friends list
        friends = new ArrayList<User>();
         
	    if (state.isOpened()) {
	    	
	    	// Request user data and show the results
	        Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

	            @Override
	            public void onCompleted(GraphUser user, Response response) {
	                if (user != null) {
	                    // Display the parsed user info
	                	profilePictureView.setProfileId(user.getId());
	                	txtUserName.setText(user.getFirstName());

	                	// Add me to friends list
	                	loggedInUser = new User();
             			loggedInUser.setId(Long.parseLong(user.getId()));
             			loggedInUser.setName(user.getName());
             			loggedInUser.setEmail(user.getProperty("email").toString());
             			
             			// Get me picture and add to friends
             			new GetUserPictureTask().execute(loggedInUser);
//	                    loggedInUser.setPicture(picture);
             			
                        new CreateUserTask().execute();
                        getFriends();
                        
                        //Old version: to update score when user retry to log in again
//                         if (isUpdateScore) {
//                         	base.updatePersonScoreAndPlace(true);
//                         	Log.i("FacebookHandler", "Call updatePersonScoreAndPlace");
//                         	isUpdateScore = false;
//                         }
	                }
	            }
	        });
	        
	        txtUserName.setVisibility(View.VISIBLE);
	    	profilePictureView.setVisibility(View.VISIBLE);
	        
	        Log.i(TAG, "Logged in...");
	    } else if (state.isClosed()) {
	    	txtUserName.setVisibility(View.INVISIBLE);
	    	profilePictureView.setVisibility(View.INVISIBLE);

	        Log.i(TAG, "Logged out...");
	    }
	}
	
	private void getFriends() {
		 
		 String fqlQuery = "SELECT uid,name FROM user WHERE uid IN(SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 1";
		 Bundle params = new Bundle();
		 params.putString("q", fqlQuery);
		 Session session = Session.getActiveSession();
		 Request request = new Request(session,"/fql",                         
	     params,                         
	     HttpMethod.GET,                 
	     new Request.Callback(){         
	       public void onCompleted(Response response) {
	           Log.i(TAG, "Result: " + response.toString());
	           GraphObject graphObject = response.getGraphObject();
               FacebookRequestError error = response.getError();
	           	
               if (graphObject.getProperty("data") != null) {
                   try {
                       // Get the data, parse info to get the key/value info
                	   JSONArray jArray = (JSONArray)graphObject.getProperty("data");
                	   
                       for(int i=0;i<jArray.length();i++){
                    	   JSONObject json_data = jArray.getJSONObject(i); 
                    	   
	                       User user = new User();
	                       user.setId(json_data.getLong("uid"));
	                       user.setName(json_data.getString("name"));
	                       
	                       // get user picture and add to friends
	                       new GetUserPictureTask().execute(user);
                       }

                   } catch (JSONException e) {
                	   e.printStackTrace();
                	   String message = "Error getting request info";
                	   Log.e(TAG, message);
                       
                   }
               } else if (error != null) {
            	   String message = "Error getting request info";
            	   Log.e(TAG, message);
               }

	       }                  
		 }); 
		 Request.executeBatchAsync(request); 
	}
	
	public void publishFeedDialog(Bundle params) {
	    params.putString("name", "Facebook SDK for Android");
	    params.putString("caption", "Build great social apps and get more installs.");
	    params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
	    params.putString("link", "https://developers.facebook.com/android");
	    params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");

	    WebDialog feedDialog = (
	        new WebDialog.FeedDialogBuilder(getActivity(),
	            Session.getActiveSession(),
	            params))
	        .setOnCompleteListener(new OnCompleteListener() {

	            @Override
	            public void onComplete(Bundle values,
	                FacebookException error) {
	                if (error == null) {
	                    // When the story is posted, echo the success
	                    // and the post Id.
	                    final String postId = values.getString("post_id");
	                    if (postId != null) {
	                        Toast.makeText(getActivity(),"Post succesful",Toast.LENGTH_SHORT).show();
	                    } else {
	                        // User clicked the Cancel button
	                        Toast.makeText(getActivity().getApplicationContext(),"No wall post made",  Toast.LENGTH_SHORT).show();
	                    }
	                } else if (error instanceof FacebookOperationCanceledException) {
	                    // User clicked the "x" button
	                    Toast.makeText(getActivity().getApplicationContext(),"Publish cancelled", Toast.LENGTH_SHORT).show();
	                } else {
	                    // Generic, ex: network error
	                    Toast.makeText(getActivity().getApplicationContext(), "Error posting", Toast.LENGTH_SHORT).show();
	                }
	            }

	        }).build();
	    
	    feedDialog.show();
	}
	
	@Override
	public void onResume() {
	    super.onResume();
	    // For scenarios where the main activity is launched and user
	    // session is not null, the session state change notification
	    // may not be triggered. Trigger it if it's open/closed.
	    Session session = Session.getActiveSession();
	    if (session != null &&
	           (session.isOpened() || session.isClosed()) ) {
	        onSessionStateChange(session, session.getState(), null);
	    }

	    uiHelper.onResume();

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onPause() {
	    super.onPause();
	    uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
	    super.onDestroy();
	    uiHelper.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
	    super.onSaveInstanceState(outState);
	    uiHelper.onSaveInstanceState(outState);
	}
	
	private class CreateUserTask extends AsyncTask<Void, Void, Void>
    {    		
		@Override
		protected Void doInBackground(Void... params) {
			RestDataHandler.CreateUser(loggedInUser);
			return null;
		}
    	
    }
	
	private class GetUserPictureTask extends AsyncTask<User, Void, Void>
    {   
		@Override
		protected Void doInBackground(User... user) {
			String imageURL = "http://graph.facebook.com/"+user[0].getId()+"/picture?type=small"; 
            Bitmap picture = Util.getUserPicture(imageURL); 
            user[0].setPicture(picture);
            friends.add(user[0]);
			return null;
		}
    	
    }

}
